﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElectronicDiary.Models.Teacher;
using ElectronicDiary.Models;
using System.Data;

namespace ElectronicDiary.Controllers
{
    [Authorize(Roles = "Teacher")]
    public class TeacherController : Controller
    {
        //
        // GET: /Teacher/
        
        public ActionResult Panel()
        {
            return View(new SubjectClassSelectModel());
        }


        public ActionResult Oceny(int cl, int su)
        {
            using (var context = new electronicDiaryEntities())
            {
                var grades = context.grade.Where(n => n.idSubject == su && n.student.idClass == cl).ToArray();
                var gradesDescr = grades.Select(n => new { Description = n.notes.Trim() }).Distinct().ToArray();
                var students = context.student.Select(n => new { Id = n.idStudent, Name = n.lastName.Trim() + " " + n.firstName.Trim() }).OrderBy(n=>n.Name).ToArray();

                int countC = gradesDescr.Count();
                int countR = students.Count();
                ColumnViewModel[] cvm = new ColumnViewModel[countC + 2];
                RowViewModel[] rvm = new RowViewModel[countR];
                
                cvm[0] = new ColumnViewModel { Name = "Uczeń", Type="U" };

                for (int i = 1; i < countC + 1; i++)
                {
                    cvm[i] = new ColumnViewModel { Name = gradesDescr[i-1].Description };
                }

                cvm[countC + 1] = new ColumnViewModel { Name = "Nowa Ocena" };

                for (int i = 0; i < countR; i++)
                {                    
                    CellValueViewModel[] cvvm = new CellValueViewModel[countC+2];
                    cvvm[0] = new CellValueViewModel { Value = students[i].Name, ID = students[i].Id, Type="U" };

                    for (int j = 1; j < countC + 1; j++)
                    {
                        var grade = grades.Single(n => n.idStudent == cvvm[0].ID && n.notes.Trim() == cvm[j].Name);

                        cvvm[j] = new CellValueViewModel { Value = grade.grade1 == null ? "" : grade.grade1.ToString(), ID = grade.idGrade };
                    }
                    cvvm[countC + 1] = new CellValueViewModel();
                    rvm[i] = new RowViewModel { Values = cvvm };
                }
                
                GradesViewModel gvm = new GradesViewModel();
                gvm.Columns = cvm;
                gvm.Rows = rvm;
                gvm.Class = context.@class.SingleOrDefault(n => n.idClass == cl).Name.Trim();
                gvm.Subject = context.subject.SingleOrDefault(n => n.idSubject == su).name.Trim();
                gvm.IDSubject = su;
                
                return View(gvm);
            }
        }

        [HttpPost]
        public ActionResult OcenyZapis(GradesViewModel gvm, bool dodajocene)
        {
            //update 
            using (var context = new electronicDiaryEntities())
            {
                int teacherid = context.teacher.SingleOrDefault(n => n.aspnet_Membership.aspnet_Users.UserName == User.Identity.Name).idTeacher;

                if (gvm.Columns.Count() > 2)
                {
                    for (int i = 1; i < gvm.Columns.Count() - 1; i++)
                    {
                        foreach (var row in gvm.Rows)
                        {
                            int GID = row.Values.Skip(i).First().ID;
                            grade gr = context.grade.SingleOrDefault(n => n.idGrade == GID);
                            if (gr.grade1 != row.Values.Skip(i).First().Value)
                            {
                                gr.grade1 = row.Values.Skip(i).First().Value;
                                gr.dt_date = DateTime.Now;
                                gr.idTeacher = teacherid;
                            }
                            context.ApplyCurrentValues<grade>("grade", gr);
                            context.SaveChanges();
                        }
                    }                    
                }

                if (dodajocene)
                {
                    foreach (var row in gvm.Rows)
                    {                        
                        grade g = grade.Creategrade(1, teacherid, row.Values.First().ID, gvm.IDSubject);
                        g.dt_date = DateTime.Now;
                        g.notes = gvm.NewGrade;
                        g.grade1 = row.Values.Last().Value;
                        context.grade.AddObject(g);
                        context.SaveChanges();
                    }
                }
                return Json(new { url = Url.Action("Oceny", new { cl = context.@class.Single(n => n.Name == gvm.Class).idClass, su = gvm.IDSubject }) });
            }            
        }

        [HttpPost]
        public ActionResult GradeValid(GradesViewModel gvm)
        {
            bool nowa = false;
            foreach (var row in gvm.Rows)
            {
                if (row.Values.Skip(gvm.Columns.Count()-1).First().Value != null)
                    nowa = true;
            }

            if (gvm.Columns.Count() > 2)
            {
                if (nowa)
                {
                    foreach (var col in gvm.Columns)
                    {
                        if (gvm.NewGrade != null && gvm.NewGrade.Trim() != "" && col.Name.Trim() == gvm.NewGrade.Trim())
                            return Content("Podaj inny opis nowej oceny!");
                    }
                    return OcenyZapis(gvm, true);
                }
                else
                    return OcenyZapis(gvm, false);
            }
            else
            {
                if (nowa && gvm.NewGrade != null && gvm.NewGrade.Trim() != "")
                    return OcenyZapis(gvm, true);
                else
                    return Content("Podaj opis i oceny!");
            }           
        }
    }
}
